package com.agileai.crm.module.procustomer.handler;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.agileai.common.KeyGenerator;
import com.agileai.crm.common.BaseExcelImportHandler;
import com.agileai.crm.cxmodule.WcmGeneralGroup8ContentManage;
import com.agileai.crm.module.procustomer.service.OrgInfoManage;
import com.agileai.domain.DataParam;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

/**
 * generated by miscdp
 */
public class ProcustUploadHandler extends BaseExcelImportHandler{
	public ProcustUploadHandler(){
		super();
        this.downloadFileName = "潜在客户.xls";
        this.templateFileName = "proCust.xls";
        this.resourceGroupId = "64D3B2E9-361E-4877-8AFE-D5DEA36BEA68";
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		this.setAttributes(param);
		this.processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
	
	protected void processPageAttributes(DataParam param){
		
	}
	
    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");

            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);

            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath(resourceGroupId);

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
				if (item.isFormField()){
					String fieldName = item.getFieldName();
					if (fieldName.equals("columnId")){
						String columnId = item.getString();
						resourceParam.put("GRP_ID",columnId);
						filePath = this.buildResourseSavePath(columnId);						
					}
					continue;
				}
                name = item.getName();
                resourceParam.put("GRP_ID", resourceGroupId);
                resourceParam.put("RES_NAME", name);

                String location = resourceRelativePath + "/" + name;
                resourceParam.put("RES_LOCATION", location);
                fileFullPath = filePath.getAbsolutePath() + File.separator +
                               name;
                setAttribute("location",location);
                long resourceSize = item.getSize();
                resourceParam.put("RES_SIZE", String.valueOf(resourceSize));

                String suffix = name.substring(name.lastIndexOf("."));
                resourceParam.put("RES_SUFFIX", suffix);
                resourceParam.put("RES_SHAREABLE", "Y");
                
                File tempFile = new File(fileFullPath);

                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                item.write(tempFile);
                
                List<DataParam> dataParams = new ArrayList<DataParam>();
                this.buildParams(tempFile,dataParams);
                
                if(null != dataParams && dataParams.size() > 0){
                	this.importRecords(dataParams);
                }
                
                this.insertResourceRecord();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new NullRenderer();
    }
	
	@PageAction
	public ViewRenderer back(DataParam param){
		return new RedirectRenderer(getHandlerURL("MainWin"));
	}

	@Override
	protected void buildParams(File uploadedFile, List<DataParam> dataParams)
			throws Exception {
    	Workbook tempWorkbook = Workbook.getWorkbook(uploadedFile);
    	KeyGenerator keyGenerator = KeyGenerator.instance();
    	Sheet sheet = tempWorkbook.getSheet(0);
    	int rows = sheet.getRows();
    	int startIndex = 1;
    	for (int i = startIndex;i < rows;i++){
    		DataParam param = new DataParam();
    		param.put("ORG_ID",keyGenerator.genKey());
    		
    		Cell nameCell = sheet.getCell(0, i);
    		String nameCellValue = nameCell.getContents();
    		param.put("ORG_NAME",nameCellValue);
    		
    		Cell introductionCell = sheet.getCell(1, i);
    		String introductionCellValue = introductionCell.getContents();
    		param.put("ORG_INTRODUCTION",introductionCellValue);
    		
    		Cell linkmanCell = sheet.getCell(2, i);
    		String linkmanCellValue = linkmanCell.getContents();
    		param.put("ORG_LINKMAN_NAME",linkmanCellValue);
    		
    		Cell contactWay1Cell = sheet.getCell(3, i);
    		String contactWay1CellValue = contactWay1Cell.getContents();
    		
    		Cell contactWay2Cell = sheet.getCell(3, i);
    		String contactWay2CellValue = contactWay2Cell.getContents();
    		if(StringUtil.isNotNullNotEmpty(contactWay1CellValue) && StringUtil.isNotNullNotEmpty(contactWay2CellValue)){
    			param.put("ORG_CONTACT_WAY",contactWay1CellValue+","+contactWay2CellValue);
    		}else if(StringUtil.isNotNullNotEmpty(contactWay1CellValue)){
    			param.put("ORG_CONTACT_WAY",contactWay1CellValue);
    		}else if(StringUtil.isNotNullNotEmpty(contactWay2CellValue)){
    			param.put("ORG_CONTACT_WAY",contactWay2CellValue);
    		}
    		
    		param.put("ORG_STATE", "0");
    		User user = (User) getUser();
    		String userId = user.getUserId();
    		param.put("ORG_SALESMAN", userId);
    		param.put("ORG_CREATER", userId);
    		String dateTime = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
    		param.put("ORG_CREATE_TIME", dateTime);
    		param.put("ORG_UPDATE_TIME", dateTime);
    		param.put("ORG_CLASSIFICATION", "UNKNOWN");
    		param.put("ORG_TYPE", "0");
    		param.put("ORG_SOURCES", "INFO_ACQUIRE");
    		param.put("ORG_LABELS", "");
    		dataParams.add(param);
    	}
    }

	@Override
	protected void importRecords(List<DataParam> dataParams) {
    	log.info("dataParams is:"+dataParams);
    	OrgInfoManage service = this.lookupService(OrgInfoManage.class);
    	for (int i=0;i<dataParams.size();i++) {
			DataParam dataParam = dataParams.get(i);
			service.createRecord(dataParam);
		}
	}
	
    private void insertResourceRecord() {
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        resourseManage.createtContentRecord("WcmGeneralResource", resourceParam);
    }
}
